package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author atguigu-mqx
 * @ClassName TrackReceiver
 * @description: TODO
 * @date 2025年04月19日
 * @version: 1.0
 */
@Component
public class TrackReceiver {

    @Autowired
    private TrackInfoService trackInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 监听更新声音播放进度
     * @param msg
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
            key = MqConst.ROUTING_TRACK_STAT_UPDATE
    ))
    public void trackStatUpdate(String msg, Message message, Channel channel){
        try {
            //  接收消息并判断
            if (!StringUtils.isEmpty(msg)){
                //  需要将消息转换为实体类;
                TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
                //  利用业务编号防止消息重复消费；保证幂等性！
                Boolean result = redisTemplate.opsForValue().setIfAbsent(trackStatMqVo.getBusinessNo(), 1, 60, TimeUnit.SECONDS);
                try {
                    if (result){
                        //  如果为true，则说明是第一次消费，可以进行业务逻辑处理；
                        //  调用服务层方法：
                        trackInfoService.trackStatUpdate(trackStatMqVo);
                    }
                } catch (Exception e) {
                    //  删除原有的key;
                    this.redisTemplate.delete(trackStatMqVo.getBusinessNo());
                }

            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //  消息确认
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
